package com.ldy.demo3;/**
 * Created by liudeyong on 2017/7/7.
 */

import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 描述：<br>
 * 版权：Copyright (c) 2011 ~ 2017<br>
 * 公司：北京活力天汇<br>
 * 作者：刘德咏<br>
 * 版本：1.0<br>
 * 创建日期：2017/7/7<br>
 */
public class LeetCode {

    /**
     *
     * 题目：
     Given an array of integers, return indices of the two numbers such that they add up to a specific target.

     You may assume that each input would have exactly one solution.

     Example:
     Given nums = [2, 7, 11, 15], target = 9,

     Because nums[0] + nums[1] = 2 + 7 = 9,
     return [0, 1].
     * @return
     */
    public int[] subject1(int[] nums, int target){
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0; i < nums.length; i++) {
            Integer index = map.get(target - nums[i]);
            if (index == null) {
               map.put(nums[i], i);
            } else {
               return new int[] {i, index};
            }
        }
        return new int[]{0, 0};
    }

    /**
     题目：
     Implement atoi to convert a string to an integer.

     Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

     Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.     * @param str
     * @return
     */
    public int myAtoi(String str, int decide) {
        Pattern p = Pattern.compile("^\\d{1,}$");
        Long data = 0L;
        if (p.matcher(str).find()) {
            char[] chars = str.toCharArray();

            for(int i = chars.length- 1; i>-1; i--) {
                data += (chars[i] - 48) * (int)Math.pow(decide, chars.length -i - 1);
            }
            if (data > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
            }
            if (data < Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;
            }
        } else {
            System.out.println("字符串不符合规范");
        }
        return data.intValue();
    }

    @Test
    public void testSubject() {
        int[] sums = new int[]{2, 11, 11, 7, 11, 15};
        int target = 9;
        int[] result = subject1(sums, target);
        System.out.println(Arrays.toString(result));
    }

    @Test
    public void testMyAtoi() {
        System.out.println(myAtoi("s145237242", 10));
    }

    public char findFirstRepeat(String A, int n) {
        // write code here
        char[] chars = A.toCharArray();
        Map<Character, Integer> maps = new HashMap<Character, Integer>();
        for (int i=0; i<chars.length; i++) {
            if (maps.containsKey(chars[i])) {
                return chars[i];
            } else {
                maps.put(chars[i], i);
            }
        }
        return ' ';
    }
}
